package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @author ybw
 * @version 1.0
 * @date 2021/12/21 21:21
 */
@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
  @Autowired private MongoTemplate mongoTemplate;
  /**
   * 新增搜索历史记录
   *
   * @param keyword
   * @param userId
   */
  @Override
  @Async
  public void insert(String keyword, Integer userId) {
    // 参数校验
    if (StringUtils.isEmpty(keyword) || userId == null) {
      log.error("参数不能为空");
      return;
    }
    // 根据用户id和keyword查询
    Query query =
        Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
    ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
    // 存在，修改时间
    if (!ObjectUtils.isEmpty(apUserSearch)) {
      // 修改时间
      apUserSearch.setCreatedTime(new Date());
      mongoTemplate.findAndReplace(query,apUserSearch);
      return;
    }

    // 根据userId查询
    List<ApUserSearch> userSearchList =
        mongoTemplate.find(
            Query.query(Criteria.where("userId").is(userId.toString()))
                .with(Sort.by(Sort.Order.desc("createdTime"))),
            ApUserSearch.class);
    // 初始化对象
    apUserSearch = new ApUserSearch();
    apUserSearch.setUserId(userId);
    apUserSearch.setKeyword(keyword);
    apUserSearch.setCreatedTime(new Date());
    if (userSearchList.size() >= 10) {
      // 总数大于10
      // 获取最后一个
      ApUserSearch apUserSearch1 = userSearchList.get(userSearchList.size() - 1);
      Query query1 = Query.query(Criteria.where("id").is(apUserSearch1.getId()));
      // 查询并替换
      mongoTemplate.findAndReplace(query1, apUserSearch);
    } else {
      // 直接添加
      mongoTemplate.save(apUserSearch);
    }
  }

  /**
   * 搜索记录
   *
   * @return
   */
  @Override
  public ResponseResult findHistory() {
    // 获取用户id
    ApUser user = ApThreadLocalUtil.getUser();
    Integer userId = user.getId();
    // 查询mongo
    Query query = Query.query(Criteria.where("userId").is(userId));
    // 排序
    query.with(Sort.by(Sort.Order.desc("createdTime")));
    List<ApUserSearch> userSearchList = mongoTemplate.find(query, ApUserSearch.class);
    if (CollectionUtils.isEmpty(userSearchList)) {
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
    return ResponseResult.okResult(userSearchList);
  }

  /**
   * 删除记录
   *
   * @param dto
   * @return
   */
  @Override
  public ResponseResult deleteHistory(HistorySearchDto dto) {
    // 1.检查参数
    if (dto.getId() == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    // 2.判断是否登录
    ApUser user = ApThreadLocalUtil.getUser();
    if (user == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
    }

    // 3.删除
    mongoTemplate.remove(
        Query.query(Criteria.where("userId").is(user.getId()).and("id").is(dto.getId())),
        ApUserSearch.class);
    return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
  }
}
